#ifndef TCP_SERVER_EVENTLOOPTHREADPOOL_H
#define TCP_SERVER_EVENTLOOPTHREADPOOL_H

#include "../../base/noncopyable.h"
#include "../../base/Types.h"

#include <functional>
#include <memory>
#include <vector>

class EventLoop;

class EventLoopThread;

class EventLoopThreadPool : muduo::noncopyable {
public:
    typedef std::function<void(EventLoop *)> ThreadInitCallback;

    EventLoopThreadPool(EventLoop *baseLoop, string nameArg);

    ~EventLoopThreadPool();

    void setThreadNum(int numThreads) { numThreads_ = numThreads; }

    void start(const ThreadInitCallback &cb = ThreadInitCallback());

    // valid after calling start()
    /// round-robin
    EventLoop *getNextLoop();

    /// with the same hash code, it will always return the same EventLoop
    EventLoop *getLoopForHash(size_t hashCode);

    std::vector<EventLoop *> getAllLoops();

    bool started() const { return started_; }

    const string &name() const { return name_; }

private:

    EventLoop *baseLoop_;
    // 基础事件循环, 当线程数量为0的时候就直接使用这个事件循环
    string name_;
    bool started_;
    // 是否已经启动了
    int numThreads_;
    int next_;
    // 下一个线程的下标, 用于取出对应的事件循环
    std::vector<std::unique_ptr<EventLoopThread>> threads_;
    // 保存事件循环线程循环集合
    std::vector<EventLoop *> loops_;
};

#endif //TCP_SERVER_EVENTLOOPTHREADPOOL_H
